<template>
  <div class="top-right-cmp" style="height: 100%;">
    <div>
      <div class="dc-left">
        <div class="dc-text">
          生产问题年度统计
          <dv-decoration3 style="width: 200px; height: 20px"/>
        </div>
      </div>
      <div style="width: 100%; height: 270px">
        <div id="ProblemCharts" style="width:100%;height:290px;"></div>
      </div>
    </div>
    <div style="height: calc((100% - 347px) / 2)">
      <div class="dc-left">
        <div class="dc-text">
          年度停工原因分布情况
          <dv-decoration3 style="width: 200px; height: 20px"/>
        </div>
      </div>
      <div style="width: 100%; height:calc(100% - 87px);">
        <div id="unCloseCharts" style="width:100%;height:100%;"></div>
      </div>
    </div>
    <div style="height: calc((100% - 347px) / 2)">
      <div class="dc-left">
        <div class="dc-text" style="padding-bottom: 10px">
          设备工具情况
          <dv-decoration3 style="width: 200px; height: 20px"/>
        </div>
      </div>
      <div style="width: 100%; height:calc(100% - 87px);">
        <div id="deviceCharts" style="width:100%;height:100%;"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts/core';

import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  SingleAxisComponent
} from 'echarts/components';
import {
  BarChart,
  GaugeChart,
  LineChart,
  CustomChart,
  PieChart
} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';
import {defineExpose, onBeforeUnmount, onMounted, ref} from "vue";
import {listNonconformingLine, listDeviceAccount, listProblemClassify} from "../../../../apis/mes/borad";

echarts.use([
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  SingleAxisComponent, // 添加单轴组件
  BarChart,
  LineChart,
  CustomChart,
  PieChart,
  GaugeChart,
  CanvasRenderer
]);
const props = defineProps({
  year: {
    type: Number,
    required: true
  }
});
const hasCalledApi = ref(false);
const interval = ref(null);
// 配置参数
const params = ref({
  startTime: '',
  endTime: ''
});
const option = ref({});
const unCloseOptions = ref({
  legend: {
    left: '70%',
    top: 'center',
    orient: 'vertical',
    textStyle: {
      color: '#fff'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b} : {c} ({d}%)'
  },
  series: [
    {
      name: '未关闭停工原因',
      type: 'pie',
      radius: '65%',
      roseType: 'radius',
      center: ['36%', '50%'],
      itemStyle: {
        borderColor: '#030409'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      label: {
        color: '#fff',
        formatter: function (val) {
          return val.value + '  ' + val.percent + '%';
        }
      },
      data: []
    }
  ]
});
const deviceColors = ref({
  '待检': '#5470c6',
  '维修': '#FF841A',
  '报废': '#E7E8EA',
  '完好': "#91CC75",
  '故障': "#EE6666",
  '遗失': '#fac858',
  '闲置': "#9a60b4",
  '降级使用': "#73C0DE"
});
const deviceOptions = ref({
  color: ["#ea7ccc", "#fc8452", "#3ba272"],
  legend: {
    left: '70%',
    top: 'center',
    orient: 'vertical',
    textStyle: {
      color: '#fff'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b} : {c} ({d}%)'
  },
  series: [
    {
      name: '设备工具情况',
      type: 'pie',
      radius: ['36%', '65%'],
      center: ['36%', '53%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderColor: '#030409',
        borderRadius: 8,
        borderWidth: 2
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      label: {
        color: '#fff',
        formatter: function (val) {
          return val.value + '  ' + val.percent + '%';
        }
      },
      data: []
    }
  ]
});
onMounted(() => {
  onMountedHandler()
});
const onMountedHandler = () => {
  hasCalledApi.value = true;
  let yearVal = props.year;
  let ProblemCharts = echarts.init(document.getElementById('ProblemCharts'));
  createProblem(ProblemCharts, yearVal);
  let deviceCharts = echarts.init(document.getElementById('deviceCharts'));
  createDataByDevice(deviceCharts, yearVal);

  let unCloseCharts = echarts.init(document.getElementById('unCloseCharts'));
  createDataByUnClose(unCloseCharts, yearVal);
  //每隔10分钟刷新数据
  interval.value = setInterval(function () {
    createProblem(ProblemCharts, yearVal);
    createDataByDevice(deviceCharts, yearVal);
    createDataByUnClose(unCloseCharts, yearVal);
  }, 1000 * 60 * 10);
};
const createProblem = (ProblemCharts, yearVal) => {
  const requestParams = {
    year: yearVal,
    ...params.value
  };
  listNonconformingLine(requestParams).then((res) => {
    let data = [];
    if (res.success) {
      data = res.obj;
    }
    let xAxisData = Object.keys(data.series);
    let serises = [];
    xAxisData.forEach(name => {
      let a;
      if ('已关闭数' === name) {
        a = {
          data: data.series[name],
          type: "line",
          name: name,
          symbol: 'triangle',
          label: {
            show: true,
            color: 'inherit'
          },
          symbolSize: 6,
        };
      } else {
        a = {
          data: data.series[name],
          type: "line",
          name: name,
          label: {
            show: true,
            color: 'inherit'
          },
          symbolSize: 6,
        };
      }
      serises.push(a);
    });
    option.value = {
      color: ['#22e159', '#18a5f1'],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      grid: {
        left: 20,
        right: 20,
        top: 20
      },
      legend: {
        bottom: 20,
        data: xAxisData,
        textStyle: {
          color: '#fff'
        }
      },
      xAxis: {
        data: res.obj.xaxis,
        boundaryGap: false,
        axisLine: {
          lineStyle: {
            color: "#fff",
          },
        },
        axisTick: {
          show: false,
        },
      },
      yAxis: {
        type: "value",
        axisTick: {
          show: false,
        },
        axisLine: {
          lineStyle: {
            color: "#fff",
          },
        },
        axisLabel: {
          show: false
        }
      },
      series: serises
    };
    ProblemCharts.setOption(option.value);
  });
};
const createDataByDevice = (deviceCharts, yearVal) => {
  const requestParams = {
    year: yearVal,
    ...params.value
  };
  listDeviceAccount(requestParams).then((res) => {
    let data = [];
    if (res.success) {
      data = res.data.map(item => {
        if (deviceColors.value[item.name]) {
          return {
            ...item,
            itemStyle: {
              color: deviceColors.value[item.name] || ''
            }
          };
        } else {
          return item;
        }
      });
    }
    deviceOptions.value.series[0].data = data;
    deviceCharts.setOption(deviceOptions.value);
  });
};
const createDataByUnClose = (unCloseCharts, yearVal) => {
  const requestParams = {
    year: yearVal,
    ...params.value
  };
  listProblemClassify(requestParams).then((res) => {
    let data = [];
    if (res.success) {
      data = res.data;
    }
    unCloseOptions.value.series[0].data = data;
    unCloseCharts.setOption(unCloseOptions.value);
  });
};
onBeforeUnmount(() => {
  if (interval.value) {
    clearInterval(interval.value); // 在Vue实例销毁前，清除时间定时器
  }
});
defineExpose({
  onMountedHandler
})
</script>

<style lang="scss" scoped>
.top-right-cmp {
  width: 28% !important;
  position: relative;
  left: -10px;
  padding: 0;
  box-sizing: border-box;

  .dc-text {
    display: flex;
    flex-direction: column;
    height: 10%;
    font-size: 20px;
    padding: 20px;
    box-sizing: border-box;
  }

  .dc-left .dc-text {
    align-items: flex-start;
    justify-content: center;
  }
}
</style>
